package huaweiod.first;

import java.util.Scanner;

/**
 * 华为OD机试真题 Java 实现【完美走位】【2022.11 Q4新题】
 * leetCode 1234
 */
public class A_2023_12_SlidingWindow {

    public static int balancedString(String s) {
        int[] chars = new int[s.length()];
        int[] counts = new int[4];
        for (int i = 0; i < s.length(); i++) {
            chars[i] = s.charAt(i) == 'W' ? 0 : s.charAt(i) == 'A' ? 1 : s.charAt(i) == 'S' ? 2 : 3;
            counts[chars[i]]++;
        }
        int n = s.length();
        int ans = n;
        for (int l = 0, r = 0; l < n; l++) {
            while (!ok(l, r, counts) && r < n) {
                --counts[chars[r++]];
            }
            if (ok(l, r, counts)) {
                ans = Math.min(ans, r - l);
            } else {
                break;
            }
            counts[chars[l]]++;
        }
        return ans;
    }

    public static boolean ok(int l, int r, int[] counts) {
        int max = Math.max(Math.max(Math.max(counts[0],counts[1]),counts[2]),counts[3]);
        int caps = 4 * max - counts[0] - counts[1] - counts[2] - counts[3];
        return r - l >= caps;
    }

    public static void main(String[] args) {
        // 处理输入
        Scanner in = new Scanner(System.in);
        String input_str = in.nextLine();
        System.out.println(balancedString(input_str));
    }
}
